﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Web;

namespace Imgur.Net.Auth
{
    public class AuthUtils
    {
        public RegisteredAuthorizationState CheckRegisteredAuthorizationTokenState(RegistrationTokenContext tokens)
        {
            bool isExpired = DateTime.Compare(DateTime.Now, tokens.Expiration) >= 0;

            if ( ! isExpired &&
                 ! string.IsNullOrEmpty(tokens.AccessToken ) &&
                 ! string.IsNullOrEmpty(tokens.RefreshToken) )
                return RegisteredAuthorizationState.AuthorizationExists;
            
            if ( isExpired && ! string.IsNullOrEmpty(tokens.RefreshToken ) )
                return RegisteredAuthorizationState.RequiresLoginExpired;

            if ( ! isExpired && 
                string.IsNullOrEmpty(tokens.AccessToken) &&
                ! string.IsNullOrEmpty(tokens.RefreshToken ) )
                return RegisteredAuthorizationState.RequiresLoginNoAccessToken;

            return RegisteredAuthorizationState.RequiresLoginNoRefreshToken;
        }

        public RegistrationTokenContext ParseOAuthResponse(Uri uri)
        {
            if ( uri == null )
                throw new ArgumentNullException("uri");


            if (! uri.Fragment.StartsWith("#"))
                throw new LoginException();

            string parameters = uri.Fragment.Substring(1);

            NameValueCollection nvParams = HttpUtility.ParseQueryString(parameters);

            return new DefaultRegistrationTokenContext(
                nvParams["access_token"],
                nvParams["refresh_token"],
                DateTime.Now.AddSeconds(
                    Convert.ToInt32(nvParams["expires_in"])));

        }
    }
}
